package com.chinatechstar.component.commons.utils;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @ClassName:EncryptUtil
 * @功能：
 * @author：wlei
 * @日期：2022/9/11-02:01
 **/
public class EncryptUtil {
    private static final String SECRETKEY = "aaaarrrrccccffff";
    /**
     * AES解密
     * @param encryptStr 密文
     * @return 明文
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr) throws Exception {
        if (StringUtils.isEmpty(encryptStr) || StringUtils.isEmpty(SECRETKEY)) {
            return null;
        }

        byte[] encryptByte = Base64
            .getDecoder().decode(encryptStr);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(SECRETKEY.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptByte);
        return new String(decryptBytes);
    }

    /**
     * AES加密
     * @param content 明文
     * @return 密文
     * @throws Exception
     */
    public static String aesEncrypt(String content) throws Exception {
        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(SECRETKEY)) {
            return null;
        }

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(SECRETKEY.getBytes(), "AES"));

        byte[] encryptStr = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptStr);
    }

    // 测试加密与解密
    public static void main(String[] args) {
        try {
            String secretKey = "aaaabbbbccccdddd";
            String content = "999317657468350464";
            String s1 = aesEncrypt(content);
            System.out.println(s1);
            String s = aesDecrypt(s1);
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
